<template>
  <div>
    <h1>页面模拟，可以加载2次数据</h1>
    <InfiniteScroll
        @load="loadMoreData"
        :scroll-delay="250"
        :scroll-distance="100"
        :scroll-immediate="true"
        :scroll-disabled="isLoading || noMoreData"
        class="scroll-container"
    >
      <div v-for="item in items" :key="item.id" class="list-item">
        {{ item.content }}
      </div>

      <div v-if="noMoreData" class="end-message">
        No more data
      </div>
    </InfiniteScroll>
  </div>

</template>

<script setup>
import {ref, onMounted} from 'vue'
import InfiniteScroll from '@/components/InfiniteScroll/InfiniteScroll.vue'

const items = ref([])
const page = ref(1)
const isLoading = ref(false)
const noMoreData = ref(false)

const loadMoreData = async () => {
  if (isLoading.value || noMoreData.value) return

  isLoading.value = true
  try {
    // 模拟 API 调用
    const newItems = await mockFetchData(page.value)

    if (newItems.length === 0) {
      noMoreData.value = true
      return
    }

    items.value = [...items.value, ...newItems]
    page.value++
  } finally {
    isLoading.value = false
  }
}

const mockFetchData = (page) => {
  return new Promise(resolve => {
    setTimeout(() => {
      const hasMore = page < 5
      resolve(
          hasMore
              ? Array.from({length: 10}, (_, i) => ({
                id: page * 10 + i,
                content: `Item ${page * 10 + i + 1}`
              }))
              : []
      )
    }, 1000)
  })
}

// 初始加载
onMounted(() => {
  loadMoreData()
})
</script>

<style scoped>
.scroll-container {
  height: 80vh;
  max-width: 600px;
  margin: 0 auto;
  border: 1px solid #eee;
}

.list-item {
  padding: 1.5rem;
  border-bottom: 1px solid #eee;
  transition: background 0.2s;
}

.list-item:hover {
  background: #f8f8f8;
}

.end-message {
  padding: 1rem;
  text-align: center;
  color: #999;
}
</style>